/**
 * @description address router
 * @author liyunfu
 */

const router = require("koa-router")();
const {
  createAddress,
  getAddressList,
  getAddressById,
  updateAddress,
} = require("../controller/address");
const { SuccessModel, ErrorModel } = require("../res-model/index");
const loginCheck = require("../middleware/loginCheck");
router.prefix("/api/user/address");

//创建收获地址
router.post("/", loginCheck, async (ctx, next) => {
  //获取用户信息
  const userInfo = ctx.session.userInfo;
  const username = userInfo.username;
  const data = ctx.request.body;

  //创建数据
  try {
    const newAddress = await createAddress(username, data);
    ctx.body = new SuccessModel(newAddress);
  } catch (error) {
    console.error(error);
    ctx.body = new ErrorModel(10004, "创建收货地址失败");
  }
});

//获取收获地址列表
router.get("/", loginCheck, async (ctx, next) => {
  const userInfo = ctx.session.userInfo;
  const username = userInfo.username;

  //获取咧白哦
  const list = await getAddressList(username);
  ctx.body = new SuccessModel(list);
});
//获取单个收货地址
router.get("/:id", loginCheck, async (ctx, next) => {
  const id = ctx.params.id;
  const address = await getAddressById(id);

  ctx.body = new SuccessModel(address);
});
//更新收获地址
router.patch("/:id", loginCheck, async (ctx, next) => {
  const id = ctx.params.id;
  const data = ctx.request.body;
  const userInfo = ctx.session.userInfo;
  const username = userInfo.username;
  //更新
  const newAddress = await updateAddress(id, username, data);
  ctx.body = new SuccessModel(newAddress);
});
module.exports = router;

// {
//   "city": "四川",
//   "department": "yy小区",
//   "houseNumber": "111号",
//   "name": "13888888888",
//   "phone": "13888888888"
// }
